import React, { useRef,useState, useEffect } from 'react';
import { Row, Col, Card, Statistic,List,Typography,message,Tabs,Table,Button,Modal, Form, Input, Select,Checkbox } from 'antd';
import ReactECharts from 'echarts-for-react';
import './index.css';
import { getYesDpTrace,getDpTrace,getAllMonitorBk,getBkTrace,getMonitorAlerts, getBkYesTrace,getBkStockList } from '../../service/apis/monitor';
import { updateMonitorStock,addMonitorStock,removeMonitorStock } from '../../service/apis/quotation';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { StockType,AlertType,AlertTypeColor } from '../../service/config';
import KLines from '@/components/klines';
import {EventSourcePolyfill} from "event-source-polyfill";
import { set } from 'lodash';


const { Title } = Typography;
const { TabPane } = Tabs;

const formatterTime = new Intl.DateTimeFormat('zh-CN', {
  hour: '2-digit',
  minute: '2-digit',
  timeZone: 'UTC'
});

const Dashboard: React.FC = () => {
  
  const [monitorDp,setMonitorDp] = useState({
    ztNum:0,
    szNum:0,
    xdNum:0,
    dtNum:0,
    qd:0,
    fValue:0,
    kqxy:0,
    zqxy:0,
    highZqxy:0,
    highKqxy:0,
    ztZqxy:0,
    ztKqxy:0,
    dbZqxy:0,
    dbKqxy:0,
    fbValue:0,
    kpYj:0,
    ztKpYj:0,
    dbKpYj:0,
    highKpYj:0,
    totalMonitor:0
  });
  const [dpTrace,setDpTrace] = useState([]);
  const [yesDpTrace,setYesDpTrace] = useState([]);
  const [selectedKey, setSelectedKey] = useState('qd');
  const [selectedName, setSelectedName] = useState('市场强度');
  const [lineData, setLineData] = useState([]);
  const [monitorBks, setMonitorBks] = useState([]);
  const [selectedBk, setSelectedBk] = useState('');
  const [selectedBkData, setSelectedBkData] = useState([]);
  const [selectedBkYesData, setSelectedBkYesData] = useState([]);
  
  const [editingRecord, setEditingRecord] = useState(null);
  const [isAddMode, setIsAddMode] = useState(false);
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isStockModalVisible, setIsStockModalVisible] = useState(false);
  const [selectedStockData, setSelectedStockData] = useState(null);
  const [ztbSelectedStockData, setZtbSelectedStockData] = useState([]);
  const [upgradeData, setUpgradeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [shortTermReminders, setShortTermReminders] = useState([]);

  const [bkStocks,setBkStocks] = useState([]);
  const [tableData, setTableData] = useState([]);

  const shortTermRemindersRef = useRef(shortTermReminders);
  const dpTraceRef = useRef(dpTrace);
  const scrollContainerRef = useRef(null);
  const [onlyShowHigh, setOnlyShowHigh] = useState(true);


  useEffect(() => {
      // 每次 shortTermReminders 更新时，更新 ref 的值
      shortTermRemindersRef.current = shortTermReminders;
      if (scrollContainerRef.current) {
          scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight;
      }
  }, [shortTermReminders]);

  useEffect(() => {
    // 每次 shortTermReminders 更新时，更新 ref 的值
    dpTraceRef.current = dpTrace;
}, [dpTrace]);

  useEffect(() => {
    // getDpInfo().then(data => {
    //   setMonitorDp(data);
    // });
    getDpTrace().then(traces => {
      setDpTrace(traces);
      setMonitorDp(traces[traces.length-1]);
      const eventSource = new EventSourcePolyfill('/api/sse/getDpTrace', {
        heartbeatTimeout: 3 * 60 * 1000,
        headers: {
            Authorization: localStorage.getItem('Authorization'),
            Accept: 'text/event-stream'
        },
        withCredentials: true,
        reconnectionDelay: 3000,})  
      eventSource.onmessage = function (event) {
        const data = JSON.parse(event.data);
        if (dpTraceRef.current[dpTraceRef.current.length - 1].curTime !== data.curTime) {
          setDpTrace((prevTraces) => [...prevTraces, data]);
          setMonitorDp(data);
        } else {
          setDpTrace((prevTraces) => {
            const newTraces = [...prevTraces];
            newTraces[newTraces.length - 1] = data;
            return newTraces;
          });
          setMonitorDp(data);
        }
      };

      eventSource.onerror = function (error) {
        console.error('EventSource failed:', error);
        eventSource.close();
      };

      return () => {
        eventSource.close();
      };
    });
    getYesDpTrace().then(traces => {
      setYesDpTrace(traces);
    });
    getMonitorAlerts().then(alerts => {
      setShortTermReminders(alerts.reverse());
      const eventSource = new EventSourcePolyfill('/api/sse/getMonitorAlert', {
        heartbeatTimeout: 3 * 60 * 1000,
        headers: {
            Authorization: localStorage.getItem('Authorization'),
            Accept: 'text/event-stream'
        },
        withCredentials: true,
        reconnectionDelay: 3000,})  
        eventSource.onmessage = function (event) {
          // 找出新的部分
          const alertsData = JSON.parse(event.data).reverse();
          // 过滤出 alertsData 中不在 shortTermReminders 里的数据
          const newEntries = alertsData.filter(newEntry => {
            return!shortTermRemindersRef.current.some(prevReminder => {
                  return prevReminder.id === newEntry.id;
              });
          });
          if(newEntries.length > 0){
            // 将新数据追加到 shortTermReminders 中
            setShortTermReminders(prevReminders => [...prevReminders,...newEntries]);
          }
      };
    
      eventSource.onerror = function (error) {
        console.error('EventSource failed:', error);
        eventSource.close();
      };
    
      return () => {
        eventSource.close();
      };
    });
    getAllMonitorBk().then(bkData => {
      if(bkData ==null || bkData.length == 0){
        return;
      }
      setMonitorBks(bkData);
      handleBkListClick(bkData[0]);
      const eventSource = new EventSourcePolyfill('/api/sse/getSseBkList', {
        heartbeatTimeout: 3 * 60 * 1000,
        headers: {
            Authorization: localStorage.getItem('Authorization'),
            Accept: 'text/event-stream'
        },
        withCredentials: true,
        reconnectionDelay: 3000,})  
      eventSource.onmessage = function (event) {
        const data = JSON.parse(event.data);
         //设置板块数据
         setMonitorBks(data);
      };

      eventSource.onerror = function (error) {
        console.error('EventSource failed:', error);
        eventSource.close();
      };

      return () => {
        eventSource.close();
      };
    });


  }, []);

  useEffect(() => {
    if (dpTrace.length > 0) {
      handleStatisticClick(selectedKey);
    }
  }, [dpTrace]);

  

  useEffect(() => {
    if (ztbSelectedStockData.length > 0) {
      generateUpgradeData();
    }
  }, [ztbSelectedStockData]);

  const generateUpgradeData = () => {
    const upgradeMap = {};

    ztbSelectedStockData.forEach((stock) => {
      const lbDesc = stock.lbDesc || '失败';
      const lbNum = Number(lbDesc.replace('连板',''))
      const nextLevel = lbDesc === '首板' ? '1进2' : Number.isNaN(lbNum)? '失败': `${lbNum}进${lbNum + 1}`;
      if (!upgradeMap[nextLevel]) {
        upgradeMap[nextLevel] = {
          key: nextLevel,
          title: nextLevel,
          count: 0,
          successRate: 0,
          stocks: [],
          successCount: 0,
        };
      }
      upgradeMap[nextLevel].count += 1;
      upgradeMap[nextLevel].stocks.push({
        name: stock.name,
        ztFlag:stock.ztFlag,
        inc: `${Number(stock.zqxy).toFixed(2)}`,
        remark: stock.remark,
      });
      if (stock.ztFlag === 1) {
        upgradeMap[nextLevel].successCount += 1;
      }
    });
    const upgradeData = Object.values(upgradeMap).map((item) => ({
      ...item,
      successRate: ((item.successCount / item.count) * 100).toFixed(2),
    }));

    setUpgradeData(upgradeData);
  };


  const convertTimeToTimestamp = (time) => {
    const [hours, minutes] = time.split(':');
    return new Date(2025, 1, 27, parseInt(hours), parseInt(minutes)).getTime();
  };

  
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
  }

  const handleStatisticClick = (dataKey: string) => {
    setSelectedKey(dataKey);
    if(dataKey === 'fbValue'){
      setSelectedName('封板资金');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.fbValue })));
    }else if(dataKey === 'qd'){
      setSelectedName('市场强度');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.qd })));
    }else if(dataKey === 'fValue'){
      setSelectedName('量能');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.fValue })));
    }else if(dataKey === 'szNum'){
      setSelectedName('上涨下跌');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.szNum,value2:item.xdNum })));
    }else if(dataKey === 'ztNum'){
      setSelectedName('涨停跌停');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.ztNum,value2:item.dtNum })));
    }else if(dataKey === 'zqxy'){
      setSelectedName('总体溢价');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.zqxy,value2:item.kqxy })));
    }else if(dataKey === 'ztZqxy'){
      setSelectedName('涨停溢价');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.ztZqxy,value2:item.ztKqxy })));
    }else if(dataKey === 'highZqxy'){
      setSelectedName('核心票溢价');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.highZqxy,value2:item.highKqxy })));
    }else if(dataKey === 'dbZqxy'){
      setSelectedName('断板溢价');
      setLineData(dpTrace.map(item => ({ curTime: item.curTime, value1: item.dbZqxy,value2:item.dbKqxy })));
    }
  };
  const handleBkListClick = (bk: any) => {
    setSelectedBk(bk);
    getBkTrace({bkcode:bk.code}).then(bkTraces => {
      setSelectedBkData(bkTraces);
    });
    getBkYesTrace({bkcode:bk.code}).then(data => {
      setSelectedBkYesData(data);
    });
    
    getBkStockList({jyr:null,bkcode:bk.code}).then(data => {
      setBkStocks(data);
      if(onlyShowHigh){
        const filteredData = data.filter(item => item.type === 'HIGH' || item.type === 'HIGH_FRONT');
        setTableData(filteredData);
      }else{
        setTableData(data);
      }
      if(bk.type === 'ztb'){
        setZtbSelectedStockData(data);
        if(ztbSelectedStockData.length > 0){
          const eventSource = new EventSourcePolyfill('/api/sse/getZtbStockList', {
            heartbeatTimeout: 3 * 60 * 1000,
            headers: {
                Authorization: localStorage.getItem('Authorization'),
                Accept: 'text/event-stream'
            },
            withCredentials: true,
            reconnectionDelay: 3000,})  
          eventSource.onmessage = function (event) {
            const ztDatas = JSON.parse(event.data);
            //设置板块数据
            setZtbSelectedStockData(ztDatas);
          };
    
          eventSource.onerror = function (error) {
            console.error('EventSource failed:', error);
            eventSource.close();
          };
    
          return () => {
            eventSource.close();
          };
        }
      }
    });
  };

  const refreshTableData = () => {
    getBkStockList({jyr:null,bkcode:selectedBk['code']}).then(data => {
      setBkStocks(data);
      if(onlyShowHigh){
        const filteredData = bkStocks.filter(item => item.type === 'HIGH' || item.type === 'HIGH_FRONT');
        setTableData(filteredData);
      }else{
        setTableData(data);
      }
    });
  };

  const handleExpand = (key: string) => {
    setExpandedKeys(expandedKeys.includes(key) ? expandedKeys.filter(k => k !== key) : [...expandedKeys, key]);
  };

  const getBarOption = () => ({
    xAxis: {
      type: 'value',
      show: false
    },
    grid: {
      left: '3%',
      right: '20%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    yAxis: {
      type: 'category',
      data: ['涨停', '上涨', '下跌', '跌停'],
      inverse: true, // 颠倒显示顺序
    },
    series: [
      {
        data: [
          { value: monitorDp.ztNum, itemStyle: { color: 'red' } },
          { value: monitorDp.szNum, itemStyle: { color: 'orange' } },
          { value: monitorDp.xdNum, itemStyle: { color: 'lightgreen' } },
          { value: monitorDp.dtNum, itemStyle: { color: 'green' } },
        ],
        type: 'bar',
        label: {
          show: true,
          position: 'right',
        },
      },
    ],
  });

  const getLineOption = () => {
    const series = [];
    if (lineData.some(item => item.value1 !== undefined)) {
      series.push({
        data: lineData.map(item => item.value1),
        type: 'line',
        smooth: true,
        itemStyle: {
          opacity: 0,
          color:'#667ecc'
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
        markLine: {
          data: [
            {
              xAxis: '09:25',
              label: {
                formatter: '09:25',
                position: 'end',
              },
              lineStyle: {
                color: 'red',
                type: 'dashed',
              },
            },
          ],
        },
      });
    }
  
    if (lineData.some(item => item.value2 !== undefined)) {
      series.push({
        data: lineData.map(item =>  item.value2),
        type: 'line',
        smooth: true,
        itemStyle: {
          opacity: 0,
           color:'#79c157'
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
        markLine: {
          data: [
            {
              xAxis: '09:25',
              label: {
                show: true,
                formatter: '09:25',
                position: 'end',
              },
              lineStyle: {
                color: 'red',
                type: 'dashed',
              },
            },
          ],
        },
      });
    }
    // 添加昨日数据系列
    if (yesDpTrace.length > 0) {
      series.push({
        data: yesDpTrace.map((item) => item[selectedKey]),
        type: 'line',
          smooth: true,
          itemStyle: {
            color: 'gray',  
            opacity: 0,
          },
          emphasis: {
            itemStyle: {
              opacity: 1,
            },
          },
      });
    }
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          axis: 'x',
        },
      },
      xAxis: {
        type: 'category',
        data: yesDpTrace.map(item => item.curTime),
        min: '09:15', // 设置 x 轴的最小值为 09:00
        max: '15:00', // 设置 x 轴的最大值为 16:00
      },
      yAxis: {
        type: 'value',
        position: 'left',
        axisLine: {
          show: true
        },
        splitArea: {
          show: true,
          areaStyle: {
            color: ['transparent', 'rgba(154, 220, 141, 0.2)', 'transparent'],
          },
        },
      },
      series: series,
    };
  };

  const getBkTraceOption = () => {
    const series = [];
  
    if (selectedBkData.length > 0) {
      series.push({
        name: '赚钱效应',
        data: selectedBkData.map(item => item.zqxy),
        type: 'line',
        smooth: true,
        itemStyle: {
          opacity: 0,
          color:'#667ecc',
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
        markLine: {
          data: [
            {
              xAxis: '09:25',
              label: {
                show: true,
                formatter: '09:25',
                position: 'end',
              },
              lineStyle: {
                color: 'red',
                type: 'dashed',
              },
            },
          ],
        },
      });
  
      series.push({
        name: '亏钱效应',
        data: selectedBkData.map(item =>  item.kqxy),
        type: 'line',
        smooth: true,
        itemStyle: {
          opacity: 0,
          color:'#79c157',
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
        markLine: {
          data: [
            {
              xAxis: '09:25',
              label: {
                show: true,
                formatter: '09:25',
                position: 'end',
              },
              lineStyle: {
                color: 'red',
                type: 'dashed',
              },
            },
          ],
        },
      });
    }

    if(selectedBkYesData.length > 0){
      series.push({
        name: '昨日赚钱效应',
        data: selectedBkYesData.map(item =>item.zqxy),
        type: 'line',
        smooth: true,
        mooth: true,
        itemStyle: {
          color: '#c6cfeb',  
          opacity: 0,
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
      });
      series.push({
        name: '昨日亏钱效应',
        data: selectedBkYesData.map(item =>item.kqxy),
        type: 'line',
        smooth: true,
        mooth: true,
        itemStyle: {
          color: '#c3e3b5',  
          opacity: 0,
        },
        emphasis: {
          itemStyle: {
            opacity: 1,
          },
        },
      });
    }
  
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          axis: 'x',
        },
      },
      legend: {
        data: ['赚钱效应', '亏钱效应'],
      },
      xAxis: {
        type: 'category',
        data: selectedBkYesData.map(item => item.curTime),
        min: '09:15', // 设置 x 轴的最小值为 09:00
        max: '15:00', // 设置 x 轴的最大值为 16:00
      },
      yAxis: {
        type: 'value',
        position: 'left',
        axisLine: {
          show: true,
        },
      },
      series: series,
    };
  };




  const realTimeMessages = [
    '实时消息1',
    '实时消息2',
    '实时消息3',
    // 更多消息...
  ];

  
  const handleEdit = (record) => {
    setIsAddMode(false);
    setEditingRecord(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };
  const handleAdd = () => {
    setIsAddMode(true);
    form.resetFields();
    setIsModalVisible(true);
  };
  const handleRemoveMonitor = (bkCode,code) => {
      // 移除监控的逻辑
      removeMonitorStock({bkCode: bkCode,code: code}).then(() => {
        message.success('移除成功');
        refreshTableData();
      }).catch(error => console.error('Error removing monitor stock:', error));
    };
  const handleOk = () => {
    // 新增股票信息的逻辑
    form.validateFields().then(values => {
      if (isAddMode) {
        // 新增股票信息的逻辑
        addMonitorStock({
          jyr: formatDate(selectedBk['jyr']),
          bkcode: selectedBk['code'],
          code: values.code,
          name:values.name,
          range: values.range,
          type: values.type,
          lbdesc: values.lbDesc,
          remark: values.remark
        }).then(() => {
          message.success('新增成功');
          setIsModalVisible(false);
          refreshTableData();
        });
      } else {
        // 更新股票信息的逻辑
        updateMonitorStock({
          jyr: formatDate(selectedBk['jyr']),
          bkcode: editingRecord.bkCode,
          code: editingRecord.code,
          range: values.range,
          type: values.type,
          nbkcode: values.bkCode,
          lbdesc: values.lbDesc,
          remark: values.remark
        }).then(() => {
          message.success('更新成功');
          setIsModalVisible(false);
          refreshTableData();
        });
      }
    }).catch(info => {
      console.log('验证失败:', info);
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const handleStockClick = (code: any) => {
    setSelectedStockData(code);
    setIsStockModalVisible(true);
  };

  const handleModalClose = () => {
    setIsStockModalVisible(false);
    setSelectedStockData(null);
  };

  const handleCheckboxChange = (e) => {
    const checked = e.target.checked;
    setOnlyShowHigh(checked);
    if (checked) {
      const filteredData = bkStocks.filter(item => item.type === 'HIGH' || item.type === 'HIGH_FRONT');
      setTableData(filteredData);
    } else {
      setTableData(bkStocks);
    }
  };

  const columns = [
    {
      title: '代码',
      align: 'center',
      dataIndex: 'code',
      key: 'code',
      render: (text: string, record: any) => (
          <div>
            <Button type="link"  onClick={() => handleStockClick(record.code)}>
              {record.code}
            </Button>
          </div>
      ),
    },
    {
      title: '股票',
      align: 'center',
      dataIndex: 'name',
      key: 'name',
      render: (text: any, record: any) => {
        const hasHighType = record.type === 'HIGH';
        const hasFrontType = record.type === 'HIGH_FRONT';
        const icon = hasHighType ? <sup style={{ color: '#cf1322' }}>★★</sup> : hasFrontType ? <sup style={{ color: '#FFA07A' }}>★</sup> : '';
        const fontWeight = hasHighType||hasFrontType ? 'bold' : 'normal';
        return (
          <span style={{ color: hasHighType ? '#cf1322' : hasFrontType? '#FFA07A':'', fontWeight }}>
            {text}
            {icon}
        </span>
        );
      },
    },
    
    
    {
      title: '涨幅',
      align: 'center',
      dataIndex: 'zqxy',
      key: 'zqxy',
      render: (text: number, record: any) => {
        let displayText = '';
        let color = '';
        let bold = '';
        displayText = text !== null && text !== undefined ? Number(text).toFixed(2) + '%' : '-';
        color = text > 0 ? '#cf1322' : '#3f8600';
        bold = record.ztFlag!=0 ? 'bold' : 'normal';
        return <span style={{ color, fontWeight: bold }}>{displayText}</span>;
      },
    },
    {
      title: '连扳描述',
      align: 'center',
      dataIndex: 'lbDesc',
      key: 'lbDesc',
      render: (text) => (
        <span style={{ color: text !== null && text !== undefined ? '#cf1322' : '#3f8600' }}>
          {text}
        </span>
      ),
    },
    {
      title: '封板资金',
      align: 'center',
      dataIndex: 'fbValue',
      key: 'fbValue',
      render: (text: number) => <span>{Number(text/100000000).toFixed(3)}亿</span>,
    },
    {
      title: '题材',
      align: 'center',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '开盘溢价',
      align: 'center',
      dataIndex: 'kpYj',
      key: 'kpYj',
      render: (text: number) => {
        let color = text > 0 ? '#cf1322' : '#3f8600';
        return <span style={{ color }}>{Number(text).toFixed(2)}</span>;
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <>
          <Button type="link" onClick={() => handleRemoveMonitor(record.bkCode,record.code)}>删除</Button>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
        </>
      ),
    },
  ];

  return (
    <div>
    <Row gutter={[10, 10]}>
      <Col span={16} id='realpart'>
        <Card title="实时看板" style={{ boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)' }}>
          <Row>
          <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'fbValue' ? 'selected' : ''}`}
              onClick={() => handleStatisticClick('fbValue')}>
                <span>封板资金：</span>
                <Statistic value={`${Number(monitorDp.fbValue/100000000).toFixed(2)}亿`} />
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'qd' ? 'selected' : ''}`} onClick={() => handleStatisticClick('qd')}>
                <span>市场强度：</span>
                <Statistic value={monitorDp.qd} />
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'fValue' ? 'selected' : ''}`} onClick={() => handleStatisticClick('fValue')}>
                <span>量能：</span>
                <Statistic value={`${Number(monitorDp.fValue/10000).toFixed(0)}万`} />
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'szNum' ? 'selected' : ''}`} onClick={() => handleStatisticClick('szNum')}>
                <span>上涨/下跌：</span>
                <span>
                    <span style={{ color:'red' }}>{monitorDp.szNum}</span>
                    {'/'}
                    <span style={{ color: 'green' }}>{monitorDp.xdNum}</span>
                </span> 
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'ztNum' ? 'selected' : ''}`} onClick={() => handleStatisticClick('ztNum')}>
                <span>涨停/跌停：</span>
                <span>
                    <span style={{ color:'red' }}>{monitorDp.ztNum}</span>
                    {'/'}
                    <span style={{ color: 'green' }}>{monitorDp.dtNum}</span>
                </span> 
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'zqxy' ? 'selected' : ''}`} onClick={() => handleStatisticClick('zqxy')}>
                <span>总体溢价：</span>
                <span>
                    <span style={{ color: monitorDp.zqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.zqxy).toFixed(2)}</span>
                    {'/'}
                    <span style={{ color: monitorDp.kqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.kqxy).toFixed(2)}</span>
                </span> 
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'ztZqxy' ? 'selected' : ''}`} onClick={() => handleStatisticClick('ztZqxy')}>
                <span>涨停溢价：</span>
                <span>
                    <span style={{ color: monitorDp.ztZqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.ztZqxy).toFixed(2)}</span>
                    {'/'}
                    <span style={{ color: monitorDp.ztKqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.ztKqxy).toFixed(2)}</span>
                </span> 
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'highZqxy' ? 'selected' : ''}`} onClick={() => handleStatisticClick('highZqxy')}>
                <span>核心溢价：</span>
                <span>
                    <span style={{ color: monitorDp.highZqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.highZqxy).toFixed(2)}</span>
                    {'/'}
                    <span style={{ color: monitorDp.highKqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.highKqxy).toFixed(2)}</span>
                </span> 
              </div>
            </Col>
            <Col span={8}>
              <div className={`statistic-box ${selectedKey === 'dbZqxy' ? 'selected' : ''}`} onClick={() => handleStatisticClick('dbZqxy')}>
                <span>断板溢价：</span>
                <span>
                    <span style={{ color: monitorDp.dbZqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.dbZqxy).toFixed(2)}</span>
                    {'/'}
                    <span style={{ color: monitorDp.dbKqxy >0 ? 'red' : 'green' }}>{Number(monitorDp.dbKqxy).toFixed(2)}</span>
                </span> 
              </div>
            </Col>
          </Row>
          <Row style={{ marginTop: '10px' }}>
            <Col span={8} id='kvolume' className="chart-container">
                <Title style={{paddingLeft:'10px'}} level={4}>涨跌统计</Title>
                <ReactECharts  option={getBarOption()} style={{ height: '300px' }} />
            </Col>
            <Col span={16} id="kline" >
                <Title style={{textAlign:'center'}} level={4}>{selectedName}</Title>
                <ReactECharts option={getLineOption()} style={{ height: '300px' }} notMerge={true}/>
            </Col>
          </Row>
          <Row id="bkrow" style={{ marginTop: '10px' }}>
            <Col span={8} id="bkList"  className="chart-container">
              <Title style={{paddingLeft:'10px'}} level={4}>板块列表</Title>
              <List
                  itemLayout="horizontal"
                  dataSource={monitorBks}
                  renderItem={item => (
                    <List.Item onClick={() => handleBkListClick(item)}  className={`list-item ${selectedBk['code'] === item.code ? 'selected' : ''}`}>
                      <List.Item.Meta
                        title={
                          <span>
                            { item.type.startsWith('kpl/jx')?`${item.name} (${item.qd}/`:`${item.name}(`}
                            <span style={{ color: item.zqxy >0 ? '#cf1322' : '#3f8600' }}>{Number(item.zqxy).toFixed(2)}/</span>
                            <span style={{ color: item.kqxy >0 ? '#cf1322' : '#3f8600' }}>{Number(item.kqxy).toFixed(2)}</span>
                            {`)`}
                        </span>
                        }
                      />
                      <div className="zt-count">{`${item.ztNum}涨停`}</div>
                    </List.Item>
                  )}

                />
            </Col>
            <Col span={16} id="bkTracePart">
                <Title style={{textAlign:'center'}} level={4}>{selectedBk['name']}</Title>
                <ReactECharts option={getBkTraceOption()} notMerge={true} style={{ height: '300px' }} />
            </Col>
          </Row>
        </Card>
      </Col>
      <Col span={8} id='stockpart'>
        <Card title="涨停晋级情况" style={{ boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)' }}>
        <List
            itemLayout="vertical"
            dataSource={upgradeData}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  title={
                    <div onClick={() => handleExpand(item.key)} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
                      {expandedKeys.includes(item.key)? <UpOutlined /> : <DownOutlined />}
                      <span style={{ marginLeft: '10px' }}>{item.title} ({`${item.successCount}/${item.count}个`})</span>
                      <span style={{ marginLeft: 'auto', color: item.successRate > 50? 'red' : 'green' }}>
                        {item.successRate}%
                      </span>
                    </div>
                  }
                />
                {expandedKeys.includes(item.key) && (
                  <List
                    itemLayout="horizontal"
                    dataSource={item.stocks}
                    renderItem={stock => (
                      <List.Item className='sub-list-item'>
                        <List.Item.Meta
                            title={
                                <div className="sub-list-item-content">
                                    <span
                                        className="sub-list-item-result"
                                        style={{
                                            border: stock.ztFlag === 1? '1px solid red' : '1px solid green',
                                            padding: '2px 5px',
                                            borderRadius: '3px',
                                            color: stock.ztFlag === 1? 'red' : 'green'
                                        }}
                                    >
                                        {stock.ztFlag === 1? '成功' : '失败'}
                                    </span>
                                    <span className="sub-list-item-text">{stock.name}</span>
                                    <span className="sub-list-item-text">
                                      {stock.inc > 0 
                                        ? <span style={{ color:'red', fontWeight: stock.ztFlag!== 0? 'bold' : 'normal' }}>{stock.inc}</span>
                                        : <span style={{ color: 'green', fontWeight: stock.ztFlag!== 0? 'bold' : 'normal' }}>{stock.inc}</span>
                                      }
                                    </span>
                                    <span className="sub-list-item-text" style={{width:'150px'}}>{stock.remark}</span>
                                </div>
                            }
                        />
                    </List.Item>
                    )}
                  />
                )}
              </List.Item>
            )}
          />
        </Card>
        <Card title="实时播报" style={{ marginTop: '10px', boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)' }}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="短线提醒" key="1">
            <div ref={scrollContainerRef} className="scroll-container">
                {shortTermReminders.map((reminder, index) => (
                    <div key={index} className="sub-list-item-content">
                        <span
                            className="sub-list-item-result"
                            style={{
                                border: '1px solid '+AlertTypeColor[reminder.targetType], 
                                padding: '2px 5px',
                                borderRadius: '3px',
                                color: AlertTypeColor[reminder.targetType] 
                            }}
                        >
                            {AlertType[reminder.targetType]}
                        </span>
                        <span className="sub-list-item-text" >{formatterTime.format(new Date(reminder.createTime))}</span>
                        <span className="sub-list-item-text" >{reminder.targetName}</span>
                        <span className="sub-list-item-text" >{reminder.content}</span>
                    </div>
                ))}
            </div>
            </TabPane>
            <TabPane tab="实时消息" key="2">
              <div className="scroll-container">
                {realTimeMessages.map((message, index) => (
                  <div key={index} className="scroll-item">{message}</div>
                ))}
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span={24}  className="chart-container">
        <div  style={{ display: 'flex', gap: '16px', marginBottom: '16px', alignItems: 'center' }}>
          <Button type="primary" onClick={handleAdd}>新增监控</Button>
          <Checkbox checked={onlyShowHigh} onChange={handleCheckboxChange}>只看核心票</Checkbox>
        </div >
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={{ pageSize: 20 }}
          style={{ marginTop: '10px' }}
        />
      </Col>
    </Row>
    <Modal
        title={isAddMode ? "新增股票信息" : "编辑股票信息"}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          {isAddMode && (
            <Form.Item
              name="code"
              label="股票代码"
              rules={[{ required: true, message: '请输入股票代码' }]}
            >
              <Input />
            </Form.Item>
            
          )}
          {isAddMode && (
            <Form.Item
            name="name"
            label="股票名称"
            rules={[{ required: true, message: '请输入股票名称' }]}
          >
            <Input />
          </Form.Item>
          )}
          <Form.Item
            name="type"
            label="地位"
            rules={[{ required: true, message: '请输入地位' }]}
          >
             <Select>
              {Object.entries(StockType).map(([key, value]) => (
                <Option key={key} value={key}>
                  {value}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="lbDesc"
            label="连扳描述"
            rules={[{ message: '请输入连扳描述' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="range"
            label="排序信息"
            rules={[{ message: '请输入排序信息' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="bkCode"
            label="板块信息"
            rules={[{ required: true, message: '请输入板块信息' }]}
          >
          <Input disabled/>  
          </Form.Item>
          <Form.Item
            name="remark"
            label="题材备注"
          >
          <Input />  
          </Form.Item>
          
        </Form>
      </Modal>

      <Modal
        title="股票K线走势图"
        visible={isStockModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
      >
        {selectedStockData && <KLines code={selectedStockData} />}
      </Modal>
    </div>
  );
}

export default Dashboard;